<?php
class JYTools{
	/*取配置
	 *@params $name 关键字
	 *@params $configPath 配置路径
	 */
	function config($name,$configPath){
		$name = explode('.',$name);
		$res = JYYaml::getInstance()->execute($configPath.$name[0].'.yml');

		$tmp = count($name);
		for($i=1;$i<$tmp;$i++){
			$res = $res[$name[$i]];
		}
		return $res;
	}

	/*记录日志
	 *@params $content 日志内容
	 *@params $logTime 是否加日志时间,默认为添加
	 *@params $filename 日志文件名,默认用配置中日志目录+当前日期
	 */
	function log($content,$logTime=true,$filename=null){
		//发布模式不记录日志
		if(RUN_MODEL=='release') return;
		if(empty($filename)) $filename = LOG_PATH.date('Ymd').'.log';
		$dirname = dirname($filename);
	
		if (!is_dir($dirname)){
			$oldumask = umask(0);
			mkdir($dirname, 0777, true);
			umask($oldumask);
		}

		if($logTime) $content ='['.$_SERVER["REMOTE_ADDR"].' '.date('Y-m-d H:i:s')."]\n".$content."\n";

		JYFile::append($filename,$content);
	}

	function error($msg){
		//没有错误日志
		if(!$msg) return;
		
		if (!is_dir(LOG_PATH)){
			$oldumask = umask(0);
			mkdir(LOG_PATH, 0777, true);
			umask($oldumask);
		}

		$date = date("H:i:s Ymd");
		$line = "[{$date}][debug]\t".print_r($msg,true)."\n";
		if(SHOW_ERROR) echo $msg;
		return error_log($line,3,LOG_PATH.date('Ymd').'.log');
	}
	/**
	 * JYPager 用于生成分页
	 *
	 * @param string $url 子页面链接 http://www.91160.com/index.php?p=_num_
	 * @param string $totalCount 记录总条数
	 * @param string $page 当前页数
	 * @param string $pageSize 每页最大记录数
	 * @param string $sep 链接字符串中页数标识
	 * @param string $style 分页样式类
	 *
	 * @return string 分页字符串
	 */
	function pager($url,$totalCount,$page=1,$pageSize=10,$sep = "_num_",$style=''){

		$pager = array();
		$pager['pageSize'] = $pageSize;
		$pager['totalCount'] = $totalCount;
		$pager['count'] = $totalCount;
		$pager['pageCount'] = ceil($pager['totalCount']/$pager['pageSize']);
		$pager['firstPage'] = 1;
		$pager['firstPageNumber'] = 1;
		$pager['lastPage'] = $pager['pageCount'];
		$pager['lastPageNumber'] = $pager['pageCount'];
		$pager['prevPage'] = ($page>1)?($page-1):$page;
		$pager['prevPageNumber'] = $pager['prevPage'];
		$pager['nextPage'] = $page<$pager['lastPage']?$page+1:$pager['lastPage'];
		$pager['nextPageNumber'] =$pager['nextPage'];
		$pager['currentPage'] = $page;
		$pager['currentPageNumber'] = $page;
		for($i=1;$i<=$pager['pageCount'];$i++){
			$pager['pagesNumber'][] = $i;
		}

		$jump_num = 5;
		if( isset($pager) && $pager["pageCount"] > 1 ){
			$out = "<div".($style?" id='{$style}'":"").">共有<font color=\"#FF0000\">".$pager["totalCount"]."</font>条记录&nbsp;";

			$out .= "<a href='".str_replace($sep, $pager["firstPageNumber"], $url)."'>首页</a> | ";
			$out .= "<a href='".str_replace($sep, $pager["prevPageNumber"], $url)."'>上一页</a> | ";
			$out .= "<a href='".str_replace($sep, $pager["nextPageNumber"], $url)."'>下一页</a> | ";
			$out .= "<a href='".str_replace($sep, $pager["lastPageNumber"], $url)."'>末页</a> &nbsp;&nbsp;";
			foreach( $pager["pagesNumber"] as $value ){
				if( $value > ( $pager["currentPageNumber"] + $jump_num ) || $value <  ( $pager["currentPageNumber"] - $jump_num ) ){

				}else{
					if( $value == $pager["currentPageNumber"] ){
						$out .= "<font color=\"#FF0000\">$value</font> ";
					}else{
						$out .= "<a href='".str_replace($sep, $value, $url)."'>$value</a> ";
					}
				}
			}
			//$out .= "跳到<input name=\"jump\" type=\"text\" size=\"4\" onkeypress=\"if(event.keyCode==13){Javascript:location.href='".str_replace($sep, "'+this.value+'", $url)."';}\" />页</div>";
			$out .="</div>";
			return $out;
		}
	}

	/**
	 * Get client ip address
	 *
	 * @return string $ip    the client ip address
	 */
	public static function getClientIp() {
		$onlineip = '';
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), '0.0.0.0')) {
			$onlineip = getenv('HTTP_CLIENT_IP');
		} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), '0.0.0.0')) {
			$onlineip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), '0.0.0.0')) {
			$onlineip = getenv('REMOTE_ADDR');
		} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], '0.0.0.0')) {
			$onlineip = $_SERVER['REMOTE_ADDR'];
		}
		return $onlineip;
	}

	/*取ip的状态信息
	 *
	 */
	private static function _ipLookup(){
		$url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=';
		$url.= self::getClientIp();
		$data = @self::callCurl($url);
		$result = json_decode($data);

		return $result->city;
	}

	/**
	 *
	 * 取客户端IP
	 */
	public static function getClientCityId($defCityId=5) {
		//读取缓存
		$cid = JYMemcache::get('_ClientCityId_'.self::getClientIp());
		if($cid) return $cid;

		$city = self::_ipLookup();
		$cid = 5;
		foreach(APIConfig::get('city') as $tid=>$c){
			if($city==$c['snKeyCode']){
				$cid = $tid;
				break;
			}
		}

		if($cid){
			JYMemcache::add('_ClientCityId_'.self::getClientIp(),$cid);
		}

		//默认
		if(!$cid) $cid = $defCityId;

		return $cid;
	}
	
	
	/*取mobile归属地的状态信息
	 *
	 */
	private static function _mobileLookup($mobile){
		$url = 'http://api.showji.com/Locating/default.aspx?output=json&m=';
		$tmp = @self::callCurl($url.$mobile);
		$result = json_decode($tmp,true);

		return $result;
	}

	/*手机号码归属及相关配置查询
	 * @param string $mobile 手机号码
	 * @return array 如 array('company'=>所属公司,'cityid'=>子站编号),手机号码不正确则反回false
	 */
	public static function mobileLookup($mobile) {
		//读取缓存
		$res = JYMemcache::get('_mobileCityId_'.$mobile);
		if($res) return $res;

		$tmp = self::_mobileLookup($mobile);
	
		if(!$tmp) return false;

		if(!$tmp['QueryResult']) return false;
		$res['company'] = $tmp['Corp'];
		$configs = APIConfig::get('city');
		foreach($configs as $cid=>$config){
			if($config['mobileKeyCode']==$tmp['City']||$config['mobileKeyCode']==$tmp['Province']){
				$res['cityid'] = $cid;				
				break;
			}
		}

		if($res){
			JYMemcache::add('_mobileCityId_'.$mobile,$res);
		}

		return $res;
	}
	
	/**
	 * 以POST方式请求地址
	 * @param $url string 请求地址
	 * @param $data $header 的content-type格式，
	 * 目前在api平台和渠道内只有用到2种格式,xml和json,text
	 */
	public static function callCurl($url,$data,$type='json',$encode='utf-8'){
		//$data = json_encode($data);
		$datatype = $type == 'xml' ? "text/xml" : "text/plain";
		$arr_header = array(
	        'Accept-Language: zh-cn',
	        'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1)',
	        'Cache-Control: no-cache',
			'Content-type: '.$datatype.'; charset='.$encode,
		);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_header);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$response = curl_exec($ch);
		if(curl_errno($ch)) {
			JYTools::error($url." ".print_r($data,true).curl_error($ch));
			return false;
		}
		curl_close($ch);
		return $response;
	}
	
	/**
	 * 实现对当个文件上传的处理
	 * Enter description here ...
	 * @param unknown_type $paramname
	 * @param unknown_type $allowed_file_exts
	 * @param unknown_type $allowed_file_size
	 * @param unknown_type $savename
	 */
	public static function upload($paramname, $allowed_file_exts, $allowed_file_size, $savefile) {
		// 错误处理
		if(!empty($_FILES[$paramname]['error'])) {
			switch($_FILES[$paramname]['error']) {
				case '1':
					$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
					break;
				case '2':
					$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
					break;
				case '3':
					$error = 'The uploaded file was only partially uploaded';
					break;
				case '4':
					$error = 'No file was uploaded.';
					break;
				default:
					$error = 'No error code avaiable';
			}
		} else {
			// 文件类型检测
			$ext = pathinfo($_FILES[$paramname]['name'], PATHINFO_EXTENSION);
			$exts = explode('|', $allowed_file_exts);
			if (!in_array($ext, $exts)) {
				$error = 'File Type Error';
				return array('state'=>0, 'msg'=>$error);
			}
			
			// 文件大小检测
			if ($_FILES[$paramname]['size'] > $allowed_file_size) {
				$error = 'File Size Error';
				return array('state'=>0, 'msg'=>$error);
			}
			
			// 移动上传文件夹
			if (is_uploaded_file($_FILES[$paramname]['tmp_name']) and move_uploaded_file($_FILES[$paramname]['tmp_name'], $savefile)) {
				$error = 'Success';
			} else {
				$error = 'File Move Error';
			}
		}
		return array('state'=>$_FILES[$paramname]['error'], 'msg'=>$error);
	}
	
	/*对数据库结果格式数组进行排序
	 * @param array $data 数据库结果格式数组,即二维数组
	 * @param string $sort 排序字符串，格式和数据库排序字符串一致，
	 * 	如DOCTOR_SORT,DOCTOR_ID DESC,表示先按DOCTOR_SORT 升序，然后按DOCTOR_ID降序排列
	 */
	function sortDBResult($data,$sort){	
		$sorts = explode(',',$sort);
		$param =  array();
		// 取得列的列表
		foreach ($data as $key => $row) {
		    foreach($sorts as $k=>$sort){
		    	$sort = spliti('[ ]+',$sort);	    	
		    	$param[$k*2][$key] = $row[$sort[0]];
		    	$param[$k*2+1] = strtoupper($sort[1])=='DESC'?SORT_DESC:SORT_ASC;
		    }
		}
		$param[] = &$data;
	
		call_user_func_array('array_multisort', $param);
		return $data;
	}

	//记录和统计时间（微秒）
	function time($start,$end='',$dec=3) {
	    // 统计时间
	    if($end){
	    	if(!isset($_ENV['ToolsG'][$end])) {
	            $_ENV['ToolsG'][$end]   =  microtime(TRUE);
	        }
	        return number_format(($_ENV['ToolsG'][$end]-$_ENV['ToolsG'][$start]),$dec);
	    }
	    // 记录时间
	    $_ENV['ToolsG'][$start]  =  microtime(TRUE);
	}
}